﻿import type { AxiosRequestConfig } from 'axios'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store/modules/user'
import { getToken,removeToken } from '../utils/auth'


//不能写在顶级上，必须用变量接受
const baseUrl = import.meta.env.VITE_APP_BASE_API;
console.log('Base API:', baseUrl);
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let token = getToken()
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Token'] =`Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log('request request use error',error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    console.log('request.js response res:',response.data)
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000 && res.code !==101) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          removeToken()
          location.reload()
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('request response use error err' + error) // for debug
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export interface RequestOptions {
  /** 当前接口权限, 不需要鉴权的接口请忽略， 格式：sys:user:add */
  permCode?: string
  /** 是否直接获取data，而忽略message等 */
  isGetDataDirectly?: boolean
  /** 请求成功是提示信息 */
  successMsg?: string
  /** 请求失败是提示信息 */
  errorMsg?: string
  /** 是否mock数据请求 */
  isMock?: boolean
  /** 接口前缀 */
  isIm?: boolean
  /** 是否外部接口 */
  isOutUrl?: boolean
  /** 当页签被关闭时是否需要取消请求 */
  needCancelRequest?: boolean
}
export const request = async <T = any>(
  config: AxiosRequestConfig,
  options: RequestOptions = {},
): Promise<T> => {
  try {
    const {
      successMsg,
      errorMsg,
      permCode,
      isGetDataDirectly = true,
      isOutUrl,
      needCancelRequest = true,
    } = options

    // 将 needCancelRequest 参数传递给 axios 配置
    config.needCancelRequest = needCancelRequest

    // 如果当前是需要鉴权的接口 并且没有权限的话 则终止请求发起
    // if (permCode && !useUserStore().perms.includes(permCode)) {
    //   return $message.error('你没有访问该接口的权限，请联系管理员！')
    // }
    // const fullUrl = getFullUrl(config, options)
    // config.url = uniqueSlash(fullUrl)
    // if (IS_PROD && !isOutUrl) {
    //   // 保持api请求的协议与当前访问的站点协议一致
    //   config.url.replace(/^https?:/g, location.protocol)
    // }
    const res = await service.request(config)
    // successMsg && $message.success(successMsg)
    // errorMsg && $message.error(errorMsg)
    // return isGetDataDirectly ? res.data : res
    return res.data
  } catch (error: any) {
    return Promise.reject(error)
  }
}

// 需要扩展 AxiosRequestConfig 类型以支持 needCancelRequest
declare module 'axios' {
  interface AxiosRequestConfig {
    needCancelRequest?: boolean
  }
}

export const requestService = service
